package com.sc.demo1.core.api.web;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sc.common.annotations.OperationLog;
import com.sc.common.annotations.WebApi;
import com.sc.common.context.DefaultBusinessContext;
import com.sc.common.dto.PageDto;
import com.sc.common.dto.WebResponseDto;
import com.sc.demo1.entity.demo.Demo;
import com.sc.demo1.entity.demo.DemoList;
import com.sc.demo1.entity.demo.DemoSearch;
import com.sc.common.entity.admin.importexport.SysImportExport;
import com.sc.common.enums.OperationLogEnum;
import com.sc.common.util.CodeGenerator;
import com.sc.common.util.MyStringUtils;
import com.sc.common.util.cache.DataDictionaryUtil;
import com.sc.demo1.core.bo.DemoBo;
import com.sc.demo1.core.service.DemoService;
import com.sc.mq.producer.Producer4routingKey;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：wust
 * @date ：Created in 2019/9/9 13:47
 * @description：
 * @version:
 */
@WebApi
@RequestMapping("/web/DemoController")
@RestController
public class DemoController {
    @Autowired
    private DemoService demoServiceImpl;


    @Autowired
    private Producer4routingKey producer4routingKey;

    @Autowired
    private DemoBo demoBo;


    @Value("${spring.rabbitmq.importexcel.exchange.name}")
    private String exchangeName;

    @Value("${spring.rabbitmq.importexcel.routing-key}")
    private String routingKey;

    @Autowired
    private Environment environment;

    @OperationLog(moduleName= OperationLogEnum.MODULE_DEMO,businessName="分页查询",operationType= OperationLogEnum.Search)
    @RequestMapping(value = "/listPage",method = RequestMethod.POST)
    public WebResponseDto listPage(@RequestBody DemoSearch search){
        WebResponseDto responseDto = new WebResponseDto();
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();
        search.setProjectId(ctx.getProjectId());
        search.setCompanyId(ctx.getBranchCompanyId());

        PageDto pageDto = search.getPageDto();
        Page page = PageHelper.startPage(pageDto.getPageNum(),pageDto.getPageSize());
        List<Demo> gateways =  demoServiceImpl.select(search);
        if(CollectionUtils.isNotEmpty(gateways)){
            List<DemoList> gatewayLists = new ArrayList<>(gateways.size());
            for (Demo gateway : gateways) {
                DemoList gatewayList = new DemoList();
                BeanUtils.copyProperties(gateway,gatewayList);
                if(gateway.getAreaId() != null){
                    gatewayList.setAreaFullName("Full Name");
                }

                gatewayList.setStatusLabel(DataDictionaryUtil.getLookupNameByCode(ctx.getLocale().toString(),gateway.getStatus()));
                gatewayList.setTypeLabel(DataDictionaryUtil.getLookupNameByCode(ctx.getLocale().toString(),gateway.getType()));
                gatewayLists.add(gatewayList);
            }
            responseDto.setLstDto(gatewayLists);
        }
        BeanUtils.copyProperties(page,pageDto);
        responseDto.setPage(pageDto);
        return responseDto;
    }

    @OperationLog(moduleName= OperationLogEnum.MODULE_DEMO,businessName="新建",operationType= OperationLogEnum.Insert)
    @RequestMapping(value = "",method = RequestMethod.POST)
    public WebResponseDto create(@RequestBody Demo entity){
        WebResponseDto responseDto = new WebResponseDto();
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        DemoSearch search = new DemoSearch();
        search.setMac(entity.getMac());
        Demo demo = demoServiceImpl.selectOne(search);
        if(demo != null){
            responseDto.setFlag(WebResponseDto.INFO_WARNING);
            responseDto.setMessage("该网关已经存在，网关MAC["+entity.getMac()+"]");
            return responseDto;
        }
        entity.setProjectId(ctx.getProjectId());
        entity.setCompanyId(ctx.getBranchCompanyId());
        entity.setCreaterId(ctx.getAccountId());
        entity.setCreaterName(ctx.getAccountName());
        entity.setCreateTime(new Date());
        entity.setIsDeleted(0);
        demoServiceImpl.insert(entity);
        return responseDto;
    }

    @OperationLog(moduleName= OperationLogEnum.MODULE_DEMO,businessName="修改",operationType= OperationLogEnum.Update)
    @RequestMapping(value = "",method = RequestMethod.PUT)
    public WebResponseDto update(@RequestBody Demo entity){
        WebResponseDto responseDto = new WebResponseDto();
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();
        entity.setModifyId(ctx.getAccountId());
        entity.setModifyName(ctx.getAccountName());
        entity.setModifyTime(new Date());
        demoServiceImpl.update(entity);
        return responseDto;
    }


    @OperationLog(moduleName= OperationLogEnum.MODULE_DEMO,businessName="删除",operationType= OperationLogEnum.Delete)
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public WebResponseDto delete(@PathVariable Long id){
        WebResponseDto responseDto = new WebResponseDto();
        demoServiceImpl.delete(id);
        return responseDto;
    }


    /**
     *
     * @param request
     * @param multipartFile
     * @return
     */
    @OperationLog(moduleName= OperationLogEnum.MODULE_DEMO,businessName="导入",operationType= OperationLogEnum.Import)
    @RequestMapping(value = "/importByExcel",method= RequestMethod.POST)
    public WebResponseDto importByExcel (HttpServletRequest request, @RequestParam(value = "file" , required = true) MultipartFile multipartFile) {
        WebResponseDto mm = new WebResponseDto();
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        String moduleName = MyStringUtils.null2String(request.getParameter("moduleName"));
        if(StringUtils.isBlank(moduleName)){
            mm.setFlag(WebResponseDto.INFO_WARNING);
            mm.setMessage("上传文件失败，模块名必须填。");
            return mm;
        }else if(!moduleName.matches("[A-Za-z0-9_]+")){
            mm.setFlag(WebResponseDto.INFO_WARNING);
            mm.setMessage("上传文件失败，模块名只能是字母、数字、下划线或三者的组合。");
            return mm;
        }


        try {
            String batchNo = CodeGenerator.genImportExportCode();
            SysImportExport sysImportExport = new SysImportExport();
            sysImportExport.setBatchNo(batchNo);
            sysImportExport.setModuleName(moduleName);
            sysImportExport.setStartTime(new Date());
            sysImportExport.setOperationType("A100601");
            sysImportExport.setStatus("A100501");
            sysImportExport.setCreaterId(ctx.getAccountId());
            sysImportExport.setCreaterName(ctx.getAccountName());
            sysImportExport.setCreateTime(new Date());


            JSONObject jsonObject = new JSONObject();
            jsonObject.put("moduleName",moduleName);
            jsonObject.put("fileBytes",multipartFile.getBytes());
            jsonObject.put("sysImportExport",sysImportExport);
            jsonObject.put("ctx",DefaultBusinessContext.getContext());
            jsonObject.put("spring.application.name",environment.getProperty("spring.application.name"));

            producer4routingKey.send(exchangeName,routingKey,jsonObject);
        }catch (IOException e){
            mm.setFlag(WebResponseDto.INFO_ERROR);
            mm.setMessage("导入失败，转换文件失败。");
            return mm;
        }
        return mm;
    }


    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public WebResponseDto detail(@PathVariable Long id){
        WebResponseDto responseDto = new WebResponseDto();
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();
        return responseDto;
    }
}
